from bot.enterprise_wechat_gpt.config.conf import *
from bot.enterprise_wechat_gpt.util.tair_util import tair_util, get_natural_day_expire_second
import datetime


def add_user(user_id):
    return tair_util.sadd("QW:Users", user_id) == 1


def add_user_today(user_id):
    add_success = tair_util.sadd("QW:Users:Today", user_id) == 1
    set_expire_days("QW:Users:Today", 1)
    return add_success


def add_user_week(user_id):
    add_success = tair_util.sadd("QW:Users:Week", user_id) == 1
    set_expire_days("QW:Users:Week", 7)
    return add_success


def add_user_week_expire(user_id):
    key = "QW:Users:WeekExpire:" + user_id
    current_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 如果该用户之前没有请求过，就设置当前时间为value，后面看到的就是第一次请求的时间
    absent = tair_util.setnx(key, current_date)
    # 只要有请求就续期7天有效期
    set_expire_days(key, 7)
    return absent


def get_all_week_user():
    keys = tair_util.keys("QW:Users:WeekExpire:*")
    return [key.split("QW:Users:WeekExpire:")[-1] for key in keys]


def set_expire_days(key, days):
    time_until = get_natural_day_expire_second(days)
    tair_util.set_expire_second(key, time_until)


def mark_new_user(uid):
    # 纪录新用户，计算转人率的时候用
    if add_user(uid):
        logging.info(f"userId:[{uid}] 大模型第一次收到请求的新用户")
    if add_user_today(uid):
        logging.info(f"userId:[{uid}] 大模型今天收到请求的新用户")
    if add_user_week_expire(uid):
        logging.info(f"userId:[{uid}] 大模型7天之内收到请求的新用户")


if __name__ == '__main__':
    print(add_user("123"))
    print(add_user_today("123"))
    print(add_user_week("123"))
